<template>
<div id="address">
    <div class="pages">
        <div v-show="action == 'show'" class="page">
            <sub-page-header title="管理收货地址"></sub-page-header>
            <div v-if="!addresses.length" class="no-address">
                <span class="iconfont icon-shouhuodizhi"></span>
                <p>您还没有添加收货地址</p>
            </div>

            <div class="addresses">
                <div v-for="(item, index) in addresses" class="address" :key="item.id">
                    <div class="info">
                        <span class="pull-left">{{item.accept_name}}</span>
                        <span class="pull-right">{{item.mobile}}</span>
                    </div>
                    <p>收货地址 : {{item.province_region.name+item.city_region.name+item.area_region.name+item.address}}</p>
                    <div class="footer">
                        <el-switch
                            v-model="item.is_default"
                            :disabled="item.is_default == 1"
                            on-text=""
                            off-text=""
                            on-color="#b21014"
                            on-value="1"
                            off-value="0"
                            @change="set_default(index)">
                        </el-switch> 设为常用地址
                        <div class="pull-right">
                            <span @click="editAddress(item)">
                                <i class="iconfont icon-bianji"></i> 编辑
                            </span>
                            <span @click="deleteAddress(index)"><i class="iconfont icon-shanchu"></i> 删除</span>
                        </div>
                    </div>
                </div>
            </div>

            <button @click="action = 'save'" class="btn-footer btn btn-normal btn-rect btn-block">新增地址</button>
        </div>
        <div v-show="action == 'save'" class="page">
            <sub-page-header :triggerBack="true" @back="action='show'" :title="activeAddress ? '编辑收货地址' : '新增收货地址'"></sub-page-header>
            <el-form ref="saveForm" class="save-form" label-position="left" label-width="80px" :model="activeAddress" :rules="rules">
                <el-form-item label="收货人" prop="accept_name">
                    <el-input v-model="activeAddress.accept_name"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="activeAddress.mobile"></el-input>
                </el-form-item>
                <el-form-item label="所在地区">
                    <el-cascader
                      :options="provinces"
                      @change="setAddressRegion"
                      @active-item-change="handleItemChange"
                      :props="cascaderProps"
                      v-model="activeAddress.selectRegions"
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="activeAddress.address"></el-input>
                </el-form-item>
                <el-form-item label="设为常用地址" label-width="100px">
                    <el-switch
                        v-model="activeAddress.is_default"
                        on-text=""
                        off-text=""
                        on-color="#b21014"
                        on-value="1"
                        off-value="0">
                    </el-switch>
                </el-form-item>

                <div class="buttons">
                    <button @click.prevent="onSave" class="btn btn-block btn-normal">保存</button>
                </div>
            </el-form>
        </div>
    </div>
    <div class="bottom-margin"></div>
</div>
</template>

<script>
import SubPageHeader from '~/components/SubPageHeader.vue';
import api from '~/api/api.js';

export default {
    components: {
        SubPageHeader
    },
    created () {
        api.get('/address/index')
        .then(response => {
            this.addresses = response.data.addresses;
        });
        api.get('/region/index')
        .then(response => {
            this.provinces = response.data.regions;
        })
    },
    data () {
        return {
            action: 'show',
            radio2: '',
            defaultAddress: 0,
            activeAddress: {
                is_default: 0,
                selectRegions: []
            },
            // 地区选择属性
            cascaderProps: {
                value: 'id',
                label: 'name'
            },
            // 省份
            provinces: [
                
            ], 
            addresses: [],
            rules: {
                accept_name: [
                    {required: true, message: '请输入收货人'},
                    {max:20, message: '收货人名称不能超过20个字符'},

                ],
                mobile: [
                    {required: true, message: '请输入手机号'},
                    {pattern: /^1[0-9]{10}$/, message: '请输入正确的手机号', trigger: 'blur'}
                ],
                address: [
                    {required: true, message: '请输入详细地址'}
                ]
            }
        }
    },
    methods: {
        // 保存改变
        onSave (event) {
            this.$refs.saveForm.validate((valid) => {
                if (valid) {
                    api.post('/address/save', this.activeAddress)
                    .then(response => {
                        if(response.data.is_default == 1) {
                            this.addresses.forEach(function (item) {
                                if (item.id != response.data.id) {
                                    item.is_default = 0;    
                                }
                            });
                        }
                        if(!this.activeAddress.id) {
                            this.addresses.push(response.data);
                            
                        } else {
                            this.activeAddress.id = false;
                        }
                        this.$message.success('保存成功');
                        this.action = 'show';

                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 设置地址的地区
        setAddressRegion (values) {
            this.activeAddress.province = values[0];
            this.activeAddress.city = values[1];
            this.activeAddress.area = values[2];
        },
        // 编辑地址
        editAddress (item) {
            this.activeAddress=item;
            this.action='save';
            item.selectRegions = [item.province, item.city, item.area];
            for(let pIndex in this.provinces) {
                if (this.provinces[pIndex].id == item.province) {
                    this.getCities(pIndex)
                    .then(cities => {
                        for(let k in cities){
                            if (cities[k].id == item.city) {
                                this.getAreas(pIndex, k);
                            }
                        }
                    });
                }
            }
        },
        // 动态加载市及区
        handleItemChange (values) {
            switch (values.length) {
                case 1:
                    for(let index in this.provinces) {
                        let item = this.provinces[index];
                        if (item.id == values[0]) {
                            this.getCities(index);
                            break;
                        }
                    }
                    break;
                case 2:
                    let pIndex = 0;
                    for(let k in this.provinces) {
                        let item = this.provinces[k];
                        if (item.id != values[0]) {
                            continue;
                        }
                        pIndex = k;
                    }
                    for(let k in this.provinces[pIndex].children) {
                        let item = this.provinces[pIndex].children[k];
                        if (item.id != values[1]) {
                            continue
                        }
                        this.getAreas(pIndex, k);
                    }
            }
        },
        getCities (index) {
            let province = this.provinces[index];
            return api.get('/region/index/'+province.id)
            .then(response => {
                province.children = response.data.regions;

                return province.children;
            });
        },
        getAreas (pIndex, cIndex) {
            let province = this.provinces[pIndex];
            let city = province.children[cIndex];
            return api.get('/region/index/'+city.id)
            .then(response => {
                city.children = response.data.regions;

                return city.children;
            });
        },
        // 设置默认地址
        set_default (index) {
            api.post('/address/set_default', {id: this.addresses[index].id})
            .then(response => {
                this.$message.success('设置成功');
            });

            this.addresses.forEach(function (item, key) {
                if (index != key) {
                    item.is_default = 0;
                }
            });
        },
        // 删除地址
        deleteAddress (index) {
            this.$confirm('您确定要删除该地址吗？', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否，点错了',
                type: 'warning'
            }).then(() => {
                api.post('/address/delete', {id: this.addresses[index].id})
                .then(response => {
                    this.$message.success('删除成功');
                })
                .catch(error => {
                    this.$message.error('删除失败');
                })
                this.addresses.splice(index, 1);
            });
        }
    }
}
</script>

<style scoped>
#address {
    height: 100%;
}

.address {
    margin-bottom: 15px;
    font-size: 15px;
    width: 100%;
}

.address .info {
    padding: 10px;
    overflow: hidden;
}

.address p {
    padding: 10px;
}

.address .footer {
    border-top: 1px solid #eaeaea;
    padding: 10px;
    color: #333;
}

.btn-footer {
    height: 50px;
    line-height: 50px;
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    padding: 0;
}

.save-form {
    padding: 15px;
}
</style>

<style>
.save-form input {
    border: none;
}

.save-form .el-form-item {
    border-bottom : 1px solid #eaeaea;
}

.el-cascader-menu {
    min-width: 100px;
}
</style>